package com.ilink.teacherservice.service.impl;

/**
 * <h3>new-ilink-java-backend</h3>
 *
 * @Description <p>用于实现资源加工函数</p>
 * @Author pengshiyao
 * @Date 2024-09-19 16:07
 **/

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ilink.ilinkcommon.domain.PO.studyservice.CourseSource;
import com.ilink.ilinkcommon.domain.PO.studyservice.FileTranscriptionTaskResponse;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.utils.BeanUtils;
import com.ilink.teacherservice.controller.videoTranscription.FileTranscriptionController;
import com.ilink.teacherservice.mapper.CourseSourceMapper;
import com.ilink.teacherservice.service.FileSourceHandleService;
import com.ilink.teacherservice.service.videoTranscription.FileTranscriptionService;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @ClassName FileSourceHandleServiceImpl
 * @Description
 * @Author pengshiyao
 * @Date 2024-09-19 16:07
 **/
@Slf4j
@RequiredArgsConstructor
@Service
public class FileSourceHandleServiceImpl implements FileSourceHandleService {

    private final FileTranscriptionService fileTransService;
    private final CourseSourceMapper courseSourceMapper;
//    private final FileTranscriptionController fileTranscriptionController;

    //进行转写任务
    @Override
    public R handlefileTrans(CourseSource courseSource, String fileUrl) {
        boolean diarization_enabled =true;
        int speaker_count=mapSpeakerTypeToNumber(courseSource.getSpeakerType());
        List<String> language=convertLanguageStringToList(courseSource.getLanguage());

        FileTranscriptionTaskResponse result = fileTransService.createFileTransTask(
            fileUrl,
            diarization_enabled,
            speaker_count,courseSource.getIsTranslated(),
            language);
        //将转写结果关联到coursesource表
        courseSource.setTaskId(result.getTaskId());
        if (result.getTaskStatus().equals("COMPLETED")){
            courseSource.setTranscriptionComplete(true);
            courseSource.setTranscriptionCompleteStatus(true);
        } else if (result.getTaskStatus().equals("FAILED")) {
            courseSource.setTranscriptionCompleteStatus(true);
            log.info("音视频{}加工失败原因{}：",result.getTaskId() ,result.getErrorMessage());
        }
        courseSourceMapper.updateById(courseSource);
        return R.ok(result);
    }
    private int mapSpeakerTypeToNumber(String speakerType) {
        switch (speakerType) {
            case "暂不体验":
                return 0;
            case "单人演讲":
                return 0;
            case "2人对话":
                return 2;
            case "多人讨论":
                return 0;
            default:
                throw new IllegalArgumentException("Unknown speaker type: " + speakerType);
        }
    }
    private List<String> convertLanguageStringToList(String languageString) {
        if (languageString == null || languageString.isEmpty()) {
            return Arrays.asList(); // 返回空列表
        }
        return Arrays.asList(languageString.split("-"));
    }

    @Async("checkVideoTaskExecutor")
    public CompletableFuture<Void> checkVideoStatusAsync(Long courseSourceId) {
        return CompletableFuture.runAsync(() -> {
            int queryNum=0;

            while (true) {
                queryNum+=1;
                boolean latest = refreshVideoStatus(courseSourceId,queryNum); // 你要轮询的函数
                log.info("文件第{}次{}状态更新中...",queryNum,courseSourceId);
                if (latest) {
                    break;
                }
                try {
                    // 等待四分钟后再检查，此时线程休眠，不会占用CPU资源
                    Thread.sleep(4 * 60 * 1000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(e);
                }
            }
        });
    }
    //另一种处理方式：使用定时任务进行查询
    // 每4分钟检查一次视频状态
//    @Scheduled(fixedRate = 4 * 60 * 1000)
//    public void checkVideoStatus() {
//        List<CourseSource> courseSourceIds = courseSourceMapper.selectList(
//                new QueryWrapper<CourseSource>().eq("transcription_complete", false)
//        ); // 获取需要检查的视频ID
//        if (courseSourceIds != null) {
//            for (CourseSource courseSourceId : courseSourceIds) {
//                log.info("正在检查文件 " + courseSourceId + " 的状态...");
//                boolean latest = refreshVideoStatus(courseSourceId.getCourseSourceId()); // 调用轮询方法
//                if (latest) {
//                    System.out.println("文件 " + courseSourceId + " 状态已更新");
//                } else {
//                    System.out.println("文件 " + courseSourceId + " 状态未更新");
//                }
//            }
//
//        }
//    }
    private boolean refreshVideoStatus(Long courseSourceId,int queryNum) {
        // 返回 true 表示文件状态已更新，轮询结束
        CourseSource courseSource = courseSourceMapper.selectById(courseSourceId);
        //特殊情况，甚至都没有上传时，不进行轮询
        if (!courseSource.getOssWriteStatus()){
            return true;
        }
        //如果加工失败，即加工已经停止
        if (courseSource.getTranscriptionCompleteStatus()){
            return true;
        }
        // 判断已上传未加工完的音视频资源的状态
        if (!courseSource.getTranscriptionComplete() ) {
            String taskId = courseSource.getTaskId();
            if (taskId != null && !taskId.isEmpty() ) {
                Jugehandlevideostate(courseSource.getTaskId(),queryNum);
                //再次查询
                courseSource = courseSourceMapper.selectById(courseSourceId);
                return courseSource.getTranscriptionComplete() || courseSource.getTranscriptionCompleteStatus();

            }
            return false;
        } //当加工状态为true时，直接返回true
        return true;
    }

    //查询转写状况，并在完成时写入转写结果
    public R Jugehandlevideostate(String taskId,int queryNum) {
//        FileTranscriptionTaskResponse result =f ileTranscriptionMapper.selectById(taskId);
//        String sourcePath=result.getOutput_mp3_path();
        CourseSource courseSource = courseSourceMapper.selectOne(new QueryWrapper<CourseSource>().eq("task_id", taskId));
        try {
            R result;
//            R result = fileTranscriptionController.getResult(taskId,courseSource.getFilesourcePath());
//            FileTranscriptionTaskResponse data = (FileTranscriptionTaskResponse) result.getData();//这种强制转化的写法是不对的，不安全的，因为这时候R里面的已经是一个object了
//            FileTranscriptionTaskResponse data = BeanUtils.copyBean(result.getData(), FileTranscriptionTaskResponse.class);
            FileTranscriptionTaskResponse data = fileTransService.getFileTransInfo(taskId, courseSource.getFilesourcePath());
            if(data != null){
                result = R.ok(data);
            }else{
                result =R.error("文件未找到"+taskId);
            }
            log.info("查询结果为："+data);//@DATA 注解器已经提供了一种 tostring方法，因此可以直接+类

            if (data.getTaskStatus().equals("COMPLETED")){
                courseSource.setTranscriptionComplete(true);
                courseSource.setTranscriptionCompleteStatus(true);
                courseSourceMapper.updateById(courseSource);
            } else if (data.getTaskStatus().equals("FAILED")) {
                courseSource.setTranscriptionCompleteStatus(true);
                courseSourceMapper.updateById(courseSource);
                log.info("音视频{}加工失败原因{}：",taskId ,data.getErrorMessage());
            }else if (queryNum>10){
                //请求结果失败也算加工失败
                courseSource.setTranscriptionCompleteStatus(true);
                courseSourceMapper.updateById(courseSource);
                log.error("第十一次请求音视频加工状态且依旧失败,视作音视频处理失败");
            }
            else if (result.getCode()==0) {
                if (queryNum>5){
                    //请求结果失败也算加工失败
                    courseSource.setTranscriptionCompleteStatus(true);
                    courseSourceMapper.updateById(courseSource);
                    log.error("第六次请求音视频加工状态且依旧失败,视作音视频处理失败");
                }
            }
            return result;
        }
        catch (Exception e) {
            log.error("查询音视频加工状态时出现异常: " + taskId, e);
            if (queryNum>5){
                //请求结果失败也算加工失败
                courseSource.setTranscriptionCompleteStatus(true);
                courseSourceMapper.updateById(courseSource);
                log.error("第六次请求音视频加工状态且请求异常,视作音视频处理失败"+e.getMessage());
            }

            return R.error("音视频处理失败");
        }

    }









}
